# -*- coding: utf-8 -*-

from odoo import models, fields, api


class CpqPartner(models.Model):
    _name = 'cpq.partner'
    _description = '客户'
    _rec_name = 'name'
    _order = 'name'

    name = fields.Char('客户名称', required=True, index=True)
    code = fields.Char('客户编号', index=True, help='客户内部编号')
    
    # 客户类型
    partner_type = fields.Selection([
        ('customer', '客户'),
        ('supplier', '供应商'),
        ('both', '客户+供应商')
    ], string='类型', default='customer', required=True)
    
    # 联系信息
    contact_name = fields.Char('联系人')
    phone = fields.Char('电话')
    email = fields.Char('邮箱')
    address = fields.Text('地址')
    
    # 业务信息
    notes = fields.Text('备注')
    active = fields.Boolean('有效', default=True)
    
    # 关联数据（使用计算字段，避免模型加载时的循环依赖）
    project_count = fields.Integer('项目数', compute='_compute_project_count', store=False)
    
    def _compute_project_count(self):
        """计算项目数量"""
        for record in self:
            # 使用 search 而不是 One2many，避免模型加载时的依赖问题
            record.project_count = self.env['cpq.project'].search_count([('partner_id', '=', record.id)])
    
    def action_view_projects(self):
        """查看该客户的项目"""
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': '项目',
            'res_model': 'cpq.project',
            'view_mode': 'list,form',
            'domain': [('partner_id', '=', self.id)],
            'context': {'default_partner_id': self.id}
        }
    
    def name_get(self):
        result = []
        for record in self:
            name = f'[{record.code}] {record.name}' if record.code else record.name
            result.append((record.id, name))
        return result

